package pixivPc.task;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import pixivPc.http.RequestUtil;
import pixivPc.http.RequestUtil.SendType;
import pixivPc.ui.Panel;

/**
 * task
 * 
 * @author wangm
 *
 */
public abstract class BaseTask {

	protected final String url;
	protected final String referer;
	protected final String param;
	protected final SendType sendType;

	/**
	 * 
	 * @param url
	 *            url
	 * @param referer
	 *            跳转源
	 * @param param
	 *            参数
	 * @param sendType
	 *            请求类型 {@link SendType}
	 */
	public BaseTask(String url, String referer, String param, SendType sendType) {
		super();
		this.url = url;
		this.referer = referer;
		this.param = param;
		this.sendType = sendType;
	}

	public String getUrl() {
		return url;
	}

	/**
	 * task处理
	 * 
	 * @param panel
	 *            目标界面 {@link Panel}
	 * @param in
	 *            目标输入流
	 */
	protected abstract void process(Panel panel, InputStream in);

	/**
	 * task处理
	 * 
	 * @param panel
	 *            目标界面 {@link Panel}
	 */
	public final void run(Panel panel) {
		InputStream in = null;
		if (url != null && !url.isEmpty()) {
			in = RequestUtil.open(url, sendType, param, referer);
		}
		process(panel, in);
	}

	/**
	 * http参数构造
	 * @param params 参数名及参数
	 * @return http参数
	 */
	public static String buildParam(String... params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.length; i++) {
			if (i % 2 == 0) {
				if (sb.length() != 0) {
					sb.append("&");
				}
				sb.append(params[i]).append("=");
			} else {
				try {
					sb.append(URLEncoder.encode(params[i], "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}

		return sb.toString();

	}
}
